<template>
  <div>
    <h1>录音示例</h1>
    <button @click="startRecording" :disabled="isRecording">开始录音</button>
    <button @click="stopRecording" :disabled="!isRecording">停止录音</button>
    <audio v-if="audioUrl" :src="audioUrl" controls></audio>
    <a v-if="audioUrl" :href="audioUrl" download="recording.wav">下载录音</a>
  </div>
</template>
<script>
import { ref } from 'vue';

export default {
  name: 'AudioRecorder',
  setup() {
    const isRecording = ref(false);
    const audioUrl = ref(null);
    let mediaRecorder;
    let audioChunks = [];

    const startRecording = async () => {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        mediaRecorder = new MediaRecorder(stream);
        mediaRecorder.start();
        isRecording.value = true;

        mediaRecorder.ondataavailable = (event) => {
          audioChunks.push(event.data);
        };

        mediaRecorder.onstop = () => {
          const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
          audioChunks = [];
          audioUrl.value = URL.createObjectURL(audioBlob);
        };
      } catch (error) {
        console.error('录音失败:', error);
      }
    };

    const stopRecording = () => {
      mediaRecorder.stop();
      isRecording.value = false;
    };

    return {
      isRecording,
      audioUrl,
      startRecording,
      stopRecording,
    };
  },
};
</script>

<style scoped>
h1 {
  font-size: 2em;
  margin-bottom: 20px;
}
button {
  margin: 5px;
  padding: 10px;
}
</style>